import React from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { withRouter, Route } from 'react-router-dom';
import { Tools, List, Button } from 'weaver-mobile';
import { Form } from 'weaver-mobile-page';
import { renderLoading, renderNoData } from '../../public/BlogUtils';
const getLabel = Tools.getLabel;

@withRouter
@inject('blogAttentionStore')
@observer
export default class CreateOrEditGroup extends React.Component {
  static defaultProps = {
    prefixCls: 'blog-center-attention-editGroup',
  }

  constructor(props) {
    super(props);
    this.state = {
      page: 'create',
      id: '',
    }
  } 

  componentWillMount() {
    const { blogAttentionStore: { attentionGroup }, location: { pathname }, match: { params } } = this.props;
    const { getBlogGroupAdd } = attentionGroup;
    if (pathname.indexOf('/edit') > -1) {
      getBlogGroupAdd(params, pathname);
      this.setState({id: params.id, page: 'edit'})
    } else {
      getBlogGroupAdd('',pathname);
    }
  }

  getFields = () => {
    const { blogAttentionStore: { attentionGroup } } = this.props;
    const { editForm } = attentionGroup;
    const { conditioninfo, isInit } = editForm;
    const fields = [];
    if (isInit) {
      toJS(conditioninfo[0].items).map((item,index) => {
        fields.push(<Form.Item
          key={item.domkey.join('__')}
          form={editForm}
          fieldConfig={item}
          onChange={editForm.onChange}
        />)
      })
      return fields;
    }
  }

  render() {
    const { prefixCls, blogAttentionStore: { attentionGroup, getMyAttentionGroup }, history } = this.props;
    const { editLoading, createBlogGroup, editBlogGroup } = attentionGroup;
    const { id, page } = this.state;
    return editLoading ? renderLoading : (
      <div className={prefixCls}>
         <Form>
          <List>{this.getFields()}</List>
        </Form>
        <Button type="primary" 
          onClick={() => {
            page === 'edit' ? editBlogGroup({groupId: id}, () => {getMyAttentionGroup();history.go(-1)}) 
            : createBlogGroup(() => {getMyAttentionGroup();history.go(-1)})
          }}
        >
          {getLabel(30986,'保存')}
        </Button>
      </div>
    )
  }
}